<template>
  <div class="app-container">
    <div v-if="!dialogInfo.visible && !detailVisible">
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-enabled>
          <el-button :disabled="!canDisabled" @click="enabled()"
            >启用</el-button
          >
        </template>
        <template v-slot:filter-disabled>
          <el-button :disabled="!canEnabled" @click="disabled()"
            >停用</el-button
          >
        </template>
        <template v-slot:filter-uploadFile>
          <el-upload
            :headers="uploadInfo.headers"
            :show-file-list="false"
            :data="uploadInfo.data"
            :on-error="uploadError"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
            :action="uploadInfo.action"
          >
            <el-button>导入模板</el-button>
          </el-upload>
        </template>
      </page-filter>
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="getDepotPage"
        :tab-index="false"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
        ><template v-slot:col-name="scope">
          <span
            class="slip-edit"
            v-if="$permission('depot:detail')"
            @click="showDetail(scope.row)"
            >{{ scope.row.name }}</span
          >
          <span class="slip-edit" v-else>{{ scope.row.name }}</span>
        </template></table-container
      >
    </div>
    <modify
      v-if="dialogInfo.visible"
      v-model:visible="dialogInfo.visible"
      :id="dialogInfo.id"
      :title="dialogInfo.title"
      @returnModify="returnModify"
    />
    <depot-details
      v-if="detailVisible"
      v-model:visible="detailVisible"
      :table-row="tableRow"
    ></depot-details>
  </div>
</template>

<script setup name="depot">
import PageFilter from '@/components/PageFilter/index'
import DepotDetails from './details'
import TableContainer from '@/components/TableContainer/index'
import {
  getDepotPage,
  setDepotsDefault,
  enableDepot,
  disableDepot,
  getDepotAll,
  enabledLocationManage,
  disableLocationManage,
  setAssetDepotsDefault,
} from '@/api/core.js'
import modify from './modify'
import { ElLoading, ElMessage } from 'element-plus'
import { exportTemplateExcel } from '@/api/pub'
import _ from 'lodash'
import axios from 'axios'
const { proxy } = getCurrentInstance()
const detailVisible = ref(false)
const tableRow = ref('')

const uploadInfo = reactive({
  action: axios.defaults.baseURL + '/core/depots/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const depotId = ref('')
const listTypeInfo = reactive({
  depotList: [],
  userList: [],
})
const filterInfo = reactive({
  query: {
    nameLike: '',
    sort: 'as_default desc,create_time desc',
    searchType: 'depot',
  },
  copyQueryMap: {},
  list: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('depot:add'),
      event: create,
    },
    {
      type: 'slot',
      label: '启用',
      value: 'enabled',
      show: proxy.$permission('depot:enabled'),
    },
    {
      type: 'slot',
      label: '停用',
      value: 'disabled',
      show: proxy.$permission('depot:enabled'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
    },
    {
      type: 'slot',
      value: 'uploadFile',
    },
    {
      type: 'input',
      label: '名称/编码',
      value: 'keyword',
      event: search,
    },
    {
      label: '用途类型',
      value: 'useTypeId',
      code: 'depot_use_type',
      type: 'select-model',
      multiple: true,
      event: search,
    },
    {
      type: 'select-model',
      label: '状态',
      value: 'status',
      code: 'enabled_type',
      event: search,
    },
    {
      type: 'select-model',
      label: '是否货位管理',
      value: 'isCargoSpaceManage',
      code: 'is_cargo_space_manage',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '名称', value: 'name', type: 'slot' },
    { label: '编码', value: 'code' },
    { label: '类型', value: 'typeValue' },
    { label: '状态', value: 'statusValue' },
    { label: '默认耗材收货仓库', value: 'asDefaultValue' },
    { label: '默认资产收货仓库', value: 'assetAsDefaultValue' },

    { label: '默认使用子盘点', value: 'defaultUseSubValue' },
    { label: '是否允许有库存冻结时盘点', value: 'allowFrozenInventoryValue' },
    { label: '所属部门', value: 'deptName' },
    { label: '用途类型', value: 'useTypeName' },
    { label: '仓库管理员', value: 'managerUserName' },
    { label: '预警通知人', value: 'warningNoticeUserName' },
    { label: '是否货位管理', value: 'isCargoSpaceManageValue' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('depot:update'),
      },
      {
        label: proxy.$t('enabled'),
        event: enabled,
        show: proxy.$permission('depot:enabled'),
        ifRender(row) {
          return row.status === 0
        },
      },
      {
        label: proxy.$t('disabled'),
        event: disabled,
        show: proxy.$permission('depot:enabled'),
        ifRender(row) {
          return row.status === 1
        },
      },
      {
        label: '启用货位管理',
        event: enabledCargoSpace,
        show: proxy.$permission('depot:enabledCargoSpace'),
        ifRender(row) {
          return row.status === 1 && row.isCargoSpaceManage === 0
        },
      },
      {
        label: '停用货位管理',
        event: disabledCargoSpace,
        show: proxy.$permission('depot:disabledCargoSpace'),
        ifRender(row) {
          return row.status === 1 && row.isCargoSpaceManage === 1
        },
      },
      {
        label: '设为默认耗材收货仓库',
        event: setDefault,
        show: proxy.$permission('depot:default'),
        ifRender(row) {
          //由于后台中存在0，1，-2的asDefault状态,所以直接判断状态不为1都是可以设置为默认的
          return (
            (!row.asDefault || row.asDefault !== 1) &&
            row.status === 1 &&
            row.useTypeId.indexOf('1') != -1
          )
        },
      },
      {
        label: '设为默认资产收货仓库',
        event: setAssetDefault,
        show: proxy.$permission('depot:assetDefault'),
        ifRender(row) {
          //由于后台中存在0，1，-2的asDefault状态,所以直接判断状态不为1都是可以设置为默认的
          return (
            (!row.asAssetDefault || row.asAssetDefault !== 1) &&
            row.status === 1 &&
            row.useTypeId.indexOf('2') != -1
          )
        },
      },
    ],
  },
})
let dialogInfo = reactive({
  id: '',
  visible: false,
  title: '',
  type: '',
})
const canDisabled = computed(() => {
  return (
    tableInfo.selections.length &&
    //后台状态值都是数字
    tableInfo.selections.filter((row) => row.status !== 0).length === 0
  )
})
const canEnabled = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter((row) => row.status !== 1).length === 0
  )
})

//表单相关
const putShelfFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '任务拆分类型',
      value: 'putSplitType',
      type: 'select-model',
      code: 'wms_put_split_type',
      checkDefault: true,
      required: true,
    },
  ],
  rules: {
    putSplitType: [
      {
        required: true,
        message: '请选择任务拆分类型',
        trigger: ['blur'],
      },
    ],
  },
  labelWidth: '120px',
})

onMounted(() => {
  getList()
})
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  tableRow.value = { ...row }
  detailVisible.value = true
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
//获取仓库列表
function getDepotList(params = {}) {
  params.idNotIn = depotId.value
  params.status = '1'
  listTypeInfo.depotList = []
  getDepotAll(params).then((resp) => {
    if (resp && resp.success) {
      const data = resp.data
      for (let item of data) {
        listTypeInfo.depotList.push({
          key: item.name,
          value: item.id,
        })
      }
    }
  })
}
// 搜索
function search() {
  // 重置分页
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
//新增
function create() {
  dialogInfo.title = '新增仓库'
  dialogInfo.visible = true
  dialogInfo.type = 'update'
  dialogInfo.id = ''
}
// 编辑
function update(data) {
  filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query)
  depotId.value = data.id
  dialogInfo.title = '修改仓库'
  dialogInfo.visible = true
  dialogInfo.type = 'update'
  dialogInfo.id = data.id
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}
function setDefault(row) {
  //设为默认
  setDepotsDefault(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function setAssetDefault(row) {
  setAssetDepotsDefault(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}

function enabled(row) {
  const ids = getIds(row)
  enableDepot(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function enabledCargoSpace(row) {
  enabledLocationManage(row.id).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function disabled(row) {
  const ids = getIds(row)
  disableDepot(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function disabledCargoSpace(row) {
  disableLocationManage(row.id).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function getIds(row) {
  if (row) {
    return [row.id]
  } else {
    return tableInfo.selections.map((value) => value.id)
  }
}
function returnModify() {
  if (dialogInfo.id) {
    filterInfo.query = proxy.$fn.deepClone(filterInfo.copyQueryMap)
    getList()
  } else {
    search()
  }
}
function beforeUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.loading.close()
    return false
  }
  return isFileType && isLt
}
function uploadSuccess(resp) {
  uploadInfo.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.loading.close()
}
function downloadTemplate() {
  exportTemplateExcel('depot_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
</script>

<style scoped></style>
